package com.nj.api.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nj.api.entity.*;
import com.nj.api.exception.MsgTipException;
import com.nj.api.mapper.AccountMapper;
import com.nj.api.mapper.BidInfoMapper;
import com.nj.api.mapper.IncomeMapper;
import com.nj.api.mapper.ProductMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {
    @Resource
    private AccountMapper accountMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private BidInfoMapper bidInfoMapper;
    @Resource
    private IncomeMapper incomeMapper;
    @Override
    public BigDecimal getBalanceByUid(User user) {
        return accountMapper.selectOne(new QueryWrapper<Account>().eq("uid", user.getId())).getAvailableMoney();
    }

    @Override
    @Transactional//开启事务,投资
    public void investment(BigDecimal bidMoney, Integer pid, Integer uid) {
        //扣减账户余额
        if (accountMapper.deduct(uid,bidMoney)==0){
            throw new MsgTipException("账户余额不足");
        }
        //扣减产品剩余投资金额
        if (productMapper.deduct(pid,bidMoney)==0){
            throw new MsgTipException("产品可投余额不足");
        }
        //添加投资记录
        BidInfo bidInfo = new BidInfo();
        bidInfo.setProdId(pid);
        bidInfo.setUid(uid);
        bidInfo.setBidMoney(bidMoney);
        bidInfoMapper.insert(bidInfo);
        //判断产品是否满标，更新产品的状态为满标，满标时间，并生成收益计划
        Product product = productMapper.selectById(pid);
             //产品剩余可投资金额小于最低起投金额即为满标
        if (product.getLeftProductMoney().compareTo(product.getBidMinLimit())==1){
            //更新产品的状态为满标，和满标时间
            product.setProductStatus(1);
            product.setProductFullTime(LocalDateTime.now());
            productMapper.updateById(product);
            //根据当前的所有投资记录生成受益计划
            Income income = new Income();
            income.setUid(uid);
            income.setProdId(pid);
            income.setBidId(bidInfo.getId());
            income.setBidMoney(bidMoney);
            income.setIncomeStatus(0);
            //收益金额=投资金额*产品利率/100/12*产品周期
            BigDecimal incomeMoney = bidMoney.multiply(product.getRate()).divide(BigDecimal.valueOf(100),2, RoundingMode.HALF_UP)
                    .divide(BigDecimal.valueOf(12),2, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(product.getCycle()));
            income.setIncomeMoney(incomeMoney);
            //收益时间=投资时间+周期
            LocalDate now = LocalDate.now().plusMonths(product.getCycle());
            income.setIncomeDate(now);
            incomeMapper.insert(income);
        }


    }
}
